import { createApp, ref } from 'vue'
import App from './App.vue'
import router from './router'

const app = createApp(App)

// 创建用户状态对象
const user = {
  isLoggedIn: false,
  name: '',
  college: '',
  itemsPosted: 0,
  itemsSold: 0,
  rating: 0,
  
  login(userData) {
    this.isLoggedIn = true
    this.name = userData.name
    this.college = userData.college
    this.itemsPosted = userData.itemsPosted || 0
    this.itemsSold = userData.itemsSold || 0
    this.rating = userData.rating || 5.0
    
    // 保存到本地存储
    localStorage.setItem('user', JSON.stringify({
      name: this.name,
      college: this.college,
      itemsPosted: this.itemsPosted,
      itemsSold: this.itemsSold,
      rating: this.rating
    }))
  },
  
  logout() {
    this.isLoggedIn = false
    this.name = ''
    this.college = ''
    this.itemsPosted = 0
    this.itemsSold = 0
    this.rating = 0
    
    // 清除本地存储
    localStorage.removeItem('user')
  }
}

// 提供用户对象给所有组件
app.provide('user', user)

// 也添加到全局属性以便在模板中使用
app.config.globalProperties.$user = user

// 尝试从本地存储恢复登录状态
const savedUser = localStorage.getItem('user')
if (savedUser) {
  const userData = JSON.parse(savedUser)
  user.login(userData)
}

app.use(router).mount('#app')// 添加全局商品列表
const items = ref([
   { 
        id: 1, 
        title: '高等数学教材', 
        price: 25, 
        image: 'book', 
        category: '教材书籍',
        description: '几乎全新，无笔记痕迹',
        seller: '张同学',
        contact: '123456',
        publishDate: '2025-07-18'
      },
      { 
        id: 2, 
        title: '二手笔记本电脑', 
        price: 1200, 
        image: 'laptop', 
        category: '电子数码',
        description: '联想小新，i5处理器，8G内存，使用两年',
        seller: '李同学',
        contact: '456789',
        publishDate: '2025-07-18'
      },
      { 
        id: 3, 
        title: '篮球', 
        price: 50, 
        image: 'basketball', 
        category: '体育用品',
        description: '斯伯丁篮球，使用半年，保存完好',
        seller: '王同学',
        contact: '789456',
        publishDate: '2025-07-18'
      },
      { 
        id: 4, 
        title: '台灯', 
        price: 30, 
        image: 'lamp', 
        category: '生活用品',
        description: 'LED护眼台灯，可调节亮度',
        seller: '赵同学',
        contact: '456123',
        publishDate: '2025-07-18'
      }
    ])

// 添加商品的方法
const addItem = (newItem) => {
  items.value.push(newItem);
};

// 提供全局商品状态
app.provide('items', items);
app.provide('addItem', addItem);